package com.hhz.stream.part3;

import org.junit.Test;

import java.time.Duration;
import java.time.Instant;
import java.util.OptionalLong;
import java.util.stream.LongStream;

/**
 * 并行流
 * 把一个内容分成多个数据块，并用不同的线程分别处理每个数据块的流
 *
 * @Author Rem
 * @Date 2020-02-14
 */

public class TestParallelStream {

    //顺序流
    @Test
    public void test() {
        Instant start = Instant.now();
        OptionalLong reduce = LongStream.range(0, 100000000000L)
                .reduce(Long::sum);
        System.out.println(reduce.getAsLong());
        Instant end = Instant.now();
        System.out.println("耗费时间:" + Duration.between(start, end).toMillis());//35282
    }



    //串行流  sequential()
    @Test
    public void test1() {
        Instant start = Instant.now();
        OptionalLong reduce = LongStream.range(0, 100000000000L)
                .sequential()
                .reduce(Long::sum);

        System.out.println(reduce.getAsLong());

        Instant end = Instant.now();
        System.out.println("耗费时间:" + Duration.between(start, end).toMillis());//35226
    }

    //并行流   parallel()
    @Test
    public void test2() {
        Instant start = Instant.now();
        OptionalLong reduce = LongStream.range(0, 100000000000L)
                .parallel()
                .reduce(Long::sum);

        System.out.println(reduce.getAsLong());

        Instant end = Instant.now();
        System.out.println("耗费时间:" + Duration.between(start, end).toMillis());//18234
    }


}



